﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using RCREEE.Library;
using System.Collections;
using RCREEE.Library.Entities;
using RCREEE.Web.Classes;
using System.IO;
using System.Web.UI.HtmlControls;
using Excel = Microsoft.Office.Interop.Excel;


namespace RCREEE.Web
{
    public partial class project : System.Web.UI.Page
    {

        //Create Datatable of all projects 
        #region variables
        DataTable dtProjects = new DataTable();
        Project Project = new Project();
        ListItem li = new ListItem();
        ListItem li1 = new ListItem();
        Lookups lookups = new Lookups();
        DataTable dtPermissions = new DataTable();
        int Key = 0;
        #endregion
        System.Windows.Forms.DataGridView Ms = new System.Windows.Forms.DataGridView();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {  // Add LanguageCode session 
                //if (Session["LanguagCode"] != null)
                //    Session.Add("LanguagCode", "1033");
                //  Session.Add("CountryId","2");


                if (Request["E"] != null)
                {
                    try
                    {
                        //get DataTable Accoriding to LanguageCode,EntityId and set it to dtProjects
                        dtProjects = Project.SelectAllProject(
                              Convert.ToInt32(Session["LanguageCode"]),
                                    Convert.ToInt32(Request["E"]));
                        Session.Add("dtProjects", dtProjects);
                        if (dtProjects.Rows.Count == 0)
                            NoData.Text = "No Data For This Entity";
                        MultiView1.ActiveViewIndex = 1;
                    }
                    catch (Exception)
                    { }
                }
                else
                {
                    CheckEntityLabel.Text = "Please,Specify a project Entity Type ";
                    CountriesDD.Visible = false;
                }

                try
                {
                    #region CountriesDD
                    try
                    {
                        li.Text = "All";
                        li.Value = "0";

                        CountriesDD.DataSource = Project.GetCountries(Convert.ToInt32(Session["LanguageCode"]));
                        CountriesDD.DataTextField = "Name";
                        CountriesDD.DataValueField = "ID";
                        CountriesDD.DataBind();
                        CountriesDD.Items.RemoveAt(0);
                        CountriesDD.Items.Insert(0, li);
                    }
                    catch (Exception) { }
                    #endregion

                    #region LanguageCodeDDl

                    try
                    {
                        LanguageCodeDDl.DataSource = Project.GetLanguageCode();
                        LanguageCodeDDl.DataTextField = "Name";
                        LanguageCodeDDl.DataValueField = "ID";
                        LanguageCodeDDl.DataBind();
                    }
                    catch (Exception ex)
                    { }
                    #endregion

                    LanguageCodeDDl.SelectedValue = Session["LanguageCode"].ToString();

                }
                catch (Exception ex)
                { }
            }

            try
            {

                #region Table Permissions
                if (Session[SessionStrings.SS_Permissions] == null)
                {
                    // Table declarations
                    dtPermissions.Columns.Add("CountryId", typeof(int));
                    dtPermissions.Columns.Add("CanAdd", typeof(bool));
                    dtPermissions.Columns.Add("CanUpdate", typeof(bool));
                    dtPermissions.Columns.Add("CanDelete", typeof(bool));

                    // New Row .. assigning permissions
                    DataRow drPermission = dtPermissions.NewRow();
                    drPermission["CountryId"] = 1;
                    drPermission["CanAdd"] = false;
                    drPermission["CanUpdate"] = false;
                    drPermission["CanDelete"] = false;

                    dtPermissions.Rows.Add(drPermission);

                    // Add table to the session object
                    Session.Add("dtPermissions", dtPermissions);
                }
                else
                {
                    dtPermissions = (DataTable)Session[SessionStrings.SS_Permissions];
                    Session.Add("dtPermissions", dtPermissions);
                }
                #endregion



                // if querystring Record not null show view 0 
                if (Request["R"] != null)
                {
                    MultiView1.ActiveViewIndex = 0;
                }
                else
                {
                    if (Request["C"] != null && Request["E"] != null)
                        Key = Convert.ToInt32(Request["C"]);
                    else
                        if (Session["CountryId"] != null && Request["E"] != null)
                            Key = Convert.ToInt32(Session["CountryId"]);

                    if (Key != 0)
                    {
                        CountriesDD.SelectedValue = Key.ToString();
                        MultiView1.ActiveViewIndex = 0;
                        MasterVeiw.DataBind();
                    }
                }
            }
            catch (Exception exc)
            { }
            if (CountriesDD.SelectedValue != "" && CountriesDD.SelectedValue != "0")
                AddNewLB.Visible = Can("Add", Convert.ToInt32(CountriesDD.SelectedValue));

            //if (CountriesDD.SelectedIndex != -1)
            //{
            //    DataTable Ds = new DataTable();
            //    int langua = Convert.ToInt32(Session["LanguageCode"]);
            //    int C = Convert.ToInt32(CountriesDD.SelectedValue);
            //    int E = Convert.ToInt32(Request["E"]);
            //    Ds = Project.SelectAllprojectByCountry(langua, C, E);

            //    Ms.DataSource = Ds;
            //}

        }

        protected void rptproject_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (Session["dtProjects"] != null)
            {
                if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
                {
                    GridView grid = (GridView)e.Item.FindControl("RepeaterVeiw");
                    try
                    {
                        // Create grid Veiw and set it to Repeater gridveiw

                        // Make Datasource of grid (dtProjects according to CountryId in HidddenField ...
                        grid.DataSource = ((DataTable)Session["dtProjects"]).Select("CountryId = " + ((HiddenField)e.Item.FindControl("hCountryId")).Value).CopyToDataTable();
                        grid.DataBind();
                    }
                    catch (Exception)
                    {
                        ((Label)e.Item.FindControl("label1")).Visible = true;
                    }
                }
            }
            //else
            //{
            //    NoData.Text = "No Data Available!";
            //    //CountriesDD.Visible = false;
            //    Language.Visible = false;
            //    LanguageCodeDDl.Visible = false;
            //    AllProject.FindControl("RepeaterVeiw").Visible = false;
            //}
        }

        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            // check if Entity request !=null and 0 not show any veiw
            if (Convert.ToInt32(Request["E"]) != 0 && (Request["E"] != null))
            {
                // check if CountriesDD !=0 it will show the grid veiw(Master) else show repeater...

                if (CountriesDD.SelectedValue != "0")
                {
                    MultiView1.ActiveViewIndex = 0;
                    MasterVeiw.DataBind();
                    DetailsVeiw.DataBind();
                    if (MasterVeiw.Rows.Count == 0)
                    {
                        NoData.Text = "No Data Available!";
                        //CountriesDD.Visible = false;
                        Language.Visible = false;
                        LanguageCodeDDl.Visible = false;

                    }
                    else
                        NoData.Visible = false;

                    if (AddNewLB.Visible == false && Session["UserId"] != null)
                        AddNewLB.Visible = true;

                }
                else
                {
                    MultiView1.ActiveViewIndex = 1;

                }
            }

        }

        private void SetFieldVisibility(
            string ItemLabelId,
            string ItemFieldId,
            string InsertLabelId,
            string InsertFieldId,
            string EditLabelId,
            string EditFieldId,
            bool Visibility)
        {
            if (DetailsVeiw.CurrentMode == FormViewMode.Edit)
            {
                if (EditLabelId != "" && DetailsVeiw.FindControl(EditLabelId) != null)
                    (DetailsVeiw.FindControl(EditLabelId)).Visible = Visibility;
                if (EditFieldId != "" && DetailsVeiw.FindControl(EditFieldId) != null)
                    (DetailsVeiw.FindControl(EditFieldId)).Visible = Visibility;
            }
            else if (DetailsVeiw.CurrentMode == FormViewMode.ReadOnly && MasterVeiw.SelectedIndex != -1)
            {
                if (ItemLabelId != "" && DetailsVeiw.FindControl(ItemLabelId) != null)
                (DetailsVeiw.FindControl(ItemLabelId)).Visible = Visibility;
                if (ItemFieldId != "" && DetailsVeiw.FindControl(ItemFieldId) != null)
                (DetailsVeiw.FindControl(ItemFieldId)).Visible = Visibility;
            }
            else if (DetailsVeiw.CurrentMode == FormViewMode.Insert)
            {
                if (InsertLabelId != "" && DetailsVeiw.FindControl(InsertLabelId) != null)
                (DetailsVeiw.FindControl(InsertLabelId)).Visible = Visibility;
                if (InsertFieldId != "" && DetailsVeiw.FindControl(InsertFieldId) != null)
                (DetailsVeiw.FindControl(InsertFieldId)).Visible = Visibility;
            }
        }
        protected void DetailsVeiw_DataBound(object sender, EventArgs e)
        {

            switch (Convert.ToInt32(Request["E"]))
            {
                #region 127
                case 127:

                    break;
                #endregion
                #region 136
                case 136:
                    try
                    {
                        if (DetailsVeiw.CurrentMode == FormViewMode.Edit)
                        {

                            ((TextBox)DetailsVeiw.FindControl("InstalledCapacity")).Visible = false;
                            ((Label)DetailsVeiw.FindControl("InstalledCapacitylb")).Visible = false;

                            ((TextBox)DetailsVeiw.FindControl("EnergyProducedPerYearRate")).Visible = false;
                            ((Label)DetailsVeiw.FindControl("Energylb")).Visible = false;

                        }
                        if (DetailsVeiw.CurrentMode == FormViewMode.ReadOnly && MasterVeiw.SelectedIndex != -1)
                        {
                            ((Label)DetailsVeiw.FindControl("InstalledCapacity")).Visible = false;
                            ((Label)DetailsVeiw.FindControl("InstalledCapacitylb")).Visible = false;

                            ((Label)DetailsVeiw.FindControl("EnergyProducedPerYearRate")).Visible = false;
                            ((Label)DetailsVeiw.FindControl("Energylb")).Visible = false;
                        }

                        if (DetailsVeiw.CurrentMode == FormViewMode.Insert)
                        {

                            ((TextBox)DetailsVeiw.FindControl("InstalledCapacity")).Visible = false;
                            ((Label)DetailsVeiw.FindControl("InstalledCapacitylb")).Visible = false;

                            ((TextBox)DetailsVeiw.FindControl("EnergyProducedPerYearRate")).Visible = false;
                            ((Label)DetailsVeiw.FindControl("Energylb")).Visible = false;


                        }

                    }
                    catch (Exception) { }
                    break;
                #endregion
                #region 39
                case 39:
                    try
                    {
                        if (DetailsVeiw.CurrentMode == FormViewMode.Edit)
                        {

                            ((TextBox)DetailsVeiw.FindControl("PickupsInstalledArea")).Visible = false;
                            ((Label)DetailsVeiw.FindControl("Arealb")).Visible = false;

                            ((TextBox)DetailsVeiw.FindControl("EnergyProducedPerYearRate")).Visible = false;
                            ((Label)DetailsVeiw.FindControl("Energylb")).Visible = false;

                        }
                        if (DetailsVeiw.CurrentMode == FormViewMode.ReadOnly && MasterVeiw.SelectedIndex != -1)
                        {
                            ((Label)DetailsVeiw.FindControl("PickupsInstalledArea")).Visible = false;
                            ((Label)DetailsVeiw.FindControl("IArealb")).Visible = false;

                            ((Label)DetailsVeiw.FindControl("EnergyProducedPerYearRate")).Visible = false;
                            ((Label)DetailsVeiw.FindControl("Energylb")).Visible = false;
                        }

                        if (DetailsVeiw.CurrentMode == FormViewMode.Insert)
                        {
                            ((TextBox)DetailsVeiw.FindControl("PickupsInstalledArea")).Visible = false;
                            ((Label)DetailsVeiw.FindControl("Arealb")).Visible = false;

                            ((TextBox)DetailsVeiw.FindControl("EnergyProducedPerYearRate")).Visible = false;
                            ((Label)DetailsVeiw.FindControl("Energylb")).Visible = false;


                        }
                    }
                    catch (Exception) { }
                    break;
                #endregion
                #region 495
                case 495:
                case 570:
                case 572:
                case 575:
                case 577:
                case 579:
                case 581:
                case 584:
                case 586:
                case 602:
                case 604:
                case 607:
                case 609:
                case 611:
                case 613:
                case 615:
                case 621:
                    try
                    {
                        SetFieldVisibility("ISectorlb", "Sector", "Sectorlb", "DropDownList3", "Sectorlb", "DropDownList1", false);

                        SetFieldVisibility("IArealb", "PickupsInstalledArea", "Arealb", "PickupsInstalledArea", "Arealb", "PickupsInstalledArea", false);
                        // Category
                        SetFieldVisibility("CAT_123", "CAT_213", "Label20", "ddEntityProject", "Label21", "ddEntityEdit", false);
                        //Status
                        SetFieldVisibility("Label2", "StatusName", "Label4", "DropDownList2", "Label4", "DropDownList2", false);

                    }
                    catch (Exception) { }
                    break;
                #endregion

                case 631:
                case 633:
                case 635:
                case 637:
                case 639:
                case 641:
                case 643:
                case 645:
                case 659:
                case 661:
                case 663:
                case 665:
                case 667:
                case 669:
                case 671:
                case 675:
                    try
                    {
                        SetFieldVisibility("ISectorlb", "Sector", "Sectorlb", "DropDownList3", "Sectorlb", "DropDownList1", false);

                        SetFieldVisibility("IArealb", "PickupsInstalledArea", "Arealb", "PickupsInstalledArea", "Arealb", "PickupsInstalledArea", false);
                        // Category
                        SetFieldVisibility("CAT_123", "CAT_213", "Label20", "ddEntityProject", "Label21", "ddEntityEdit", false);
                        //Status
                        SetFieldVisibility("Label2", "StatusName", "Label4", "DropDownList2", "Label4", "DropDownList2", false);
                        // construction cpmpanies
                        SetFieldVisibility("Label3", "ConstructionCompanies", "Label5", "TextBox1", "Label5", "TextBox1", false);

                    }
                    catch (Exception) { }
                    break;
                #region 498
                case 589:
                case 591:
                case 593:
                case 595:
                case 597:
                case 599:
                    try
                    {
                        SetFieldVisibility("Energylb", "EnergyProducedPerYearRate", "Energylb", "EnergyProducedPerYearRate", "Energylb", "EnergyProducedPerYearRate", false);
                        SetFieldVisibility("IArealb", "PickupsInstalledArea", "Arealb", "PickupsInstalledArea", "Arealb", "PickupsInstalledArea", false);
                        SetFieldVisibility("InstalledCapacitylb", "InstalledCapacity", "InstalledCapcitylb", "InstalledCapacity", "InstalledCapacitylb", "InstalledCapacity", false);

                        // Category
                        SetFieldVisibility("CAT_123", "CAT_213", "Label20", "ddEntityProject", "Label21", "ddEntityEdit", false);
                        //Status
                        SetFieldVisibility("Label2", "StatusName", "Label4", "DropDownList2", "Label4", "DropDownList2", false);

                    }
                    catch (Exception) { }
                    break;

                case 647:
                case 649:
                case 651:
                case 653:
                case 655:
                case 657:
                    try
                    {
                        SetFieldVisibility("Energylb", "EnergyProducedPerYearRate", "Energylb", "EnergyProducedPerYearRate", "Energylb", "EnergyProducedPerYearRate", false);
                        SetFieldVisibility("IArealb", "PickupsInstalledArea", "Arealb", "PickupsInstalledArea", "Arealb", "PickupsInstalledArea", false);
                        SetFieldVisibility("InstalledCapacitylb", "InstalledCapacity", "InstalledCapcitylb", "InstalledCapacity", "InstalledCapacitylb", "InstalledCapacity", false);

                        // Category
                        SetFieldVisibility("CAT_123", "CAT_213", "Label20", "ddEntityProject", "Label21", "ddEntityEdit", false);
                        //Status
                        SetFieldVisibility("Label2", "StatusName", "Label4", "DropDownList2", "Label4", "DropDownList2", false);
                        // construction cpmpanies
                        SetFieldVisibility("Label3", "ConstructionCompanies", "Label5", "TextBox1", "Label5", "TextBox1", false);

                    }
                    catch (Exception) { }
                    break;

                case 618:
                    try
                    {
                        SetFieldVisibility("Energylb", "EnergyProducedPerYearRate", "Energylb", "EnergyProducedPerYearRate", "Energylb", "EnergyProducedPerYearRate", false);
                        SetFieldVisibility("IArealb", "PickupsInstalledArea", "Arealb", "PickupsInstalledArea", "Arealb", "PickupsInstalledArea", false);

                        // Category
                        SetFieldVisibility("CAT_123", "CAT_213", "Label20", "ddEntityProject", "Label21", "ddEntityEdit", false);
                        //Status
                        SetFieldVisibility("Label2", "StatusName", "Label4", "DropDownList2", "Label4", "DropDownList2", false);

                    }
                    catch (Exception) { }
                    break;

                case 673:
                    try
                    {
                        SetFieldVisibility("Energylb", "EnergyProducedPerYearRate", "Energylb", "EnergyProducedPerYearRate", "Energylb", "EnergyProducedPerYearRate", false);
                        SetFieldVisibility("IArealb", "PickupsInstalledArea", "Arealb", "PickupsInstalledArea", "Arealb", "PickupsInstalledArea", false);

                        // Category
                        SetFieldVisibility("CAT_123", "CAT_213", "Label20", "ddEntityProject", "Label21", "ddEntityEdit", false);
                        //Status
                        SetFieldVisibility("Label2", "StatusName", "Label4", "DropDownList2", "Label4", "DropDownList2", false);
                        // construction cpmpanies
                        SetFieldVisibility("Label3", "ConstructionCompanies", "Label5", "TextBox1", "Label5", "TextBox1", false);
                    }
                    catch (Exception) { }
                    break;
                #endregion
            }

            //   ((Table)DetailsVeiw.FindControl("table1")).Rows[0].Visible = false;
            //check if Detailsveiw in Edit mode ...Bind ExecutingAgencyId from Hiddenfield to ddExecutingAgency
            if (DetailsVeiw.CurrentMode == FormViewMode.Edit)
            {
                try
                {


                    ((DropDownList)DetailsVeiw.FindControl("ddTypeEdit")).SelectedValue = ((HiddenField)DetailsVeiw.FindControl("ProjectTypeId")).Value;
                    ((DropDownList)DetailsVeiw.FindControl("ddExecutingAgency")).SelectedValue = ((HiddenField)DetailsVeiw.FindControl("ExecutingAgencyId")).Value;
                    //((DropDownList)DetailsVeiw.FindControl("ddCountryEdit")).SelectedValue = ((HiddenField)DetailsVeiw.FindControl("ExecCountry")).Value;
                    //((DropDownList)DetailsVeiw.FindControl("ddEntityEdit")).SelectedValue = ((HiddenField)DetailsVeiw.FindControl("ExecEntity")).Value;
                    //((DropDownList)DetailsVeiw.FindControl("ddExecutingAgency")).DataBind();

                }
                catch (Exception)
                {

                }
            }
            if (DetailsVeiw.CurrentMode == FormViewMode.ReadOnly)
            {
                LanguageCodeDDl.Visible = false;
                Language.Visible = false;
                if (CountriesDD.SelectedValue != "0")
                {
                    try
                    {

                        ((Button)(DetailsVeiw.FindControl("DeleteButton"))).Visible = Can("Delete", Convert.ToInt32(CountriesDD.SelectedValue));
                        ((LinkButton)(DetailsVeiw.FindControl("NewButton"))).Visible = Can("Add", Convert.ToInt32(CountriesDD.SelectedValue));
                        ((LinkButton)(DetailsVeiw.FindControl("EditButton"))).Visible = Can("Update", Convert.ToInt32(CountriesDD.SelectedValue));

                    }
                    catch (Exception exp)
                    { }
                }
            }
            if (MasterVeiw.SelectedValue == null || MasterVeiw.SelectedIndex == -1)
                AddNewLB.Visible = Can("Add", Convert.ToInt32(CountriesDD.SelectedValue));
            else if (Can("Add", Convert.ToInt32(CountriesDD.SelectedValue)))
            {
                AddNewLB.Visible = !DetailsVeiw.Visible;
            }
            if (DetailsVeiw.CurrentMode == FormViewMode.Insert)
            {
                ((DropDownList)(DetailsVeiw.FindControl("ddEntityProject"))).SelectedValue = Convert.ToString(Request["E"]);
                ((DropDownList)(DetailsVeiw.FindControl("ddEntityProject"))).Enabled = false;
            }

        }

        protected void AddNewLB_Click1(object sender, EventArgs e)
        {// Add button to show the form view(Details) on insert mode...
            MasterVeiw.SelectedIndex = -1;
            DetailsVeiw.ChangeMode(FormViewMode.Insert);
            NoData.Visible = false;
            Language.Visible = true;
            LanguageCodeDDl.Visible = true;
        }

        protected void DetailsVeiw_ItemInserted(object sender, FormViewInsertedEventArgs e)
        {
            Session.Remove("dtProjects");
            dtProjects = Project.SelectAllProject(
                       Convert.ToInt32(Session["LanguageCode"]),
                             Convert.ToInt32(Request["E"]));
            Session.Add("dtProjects", dtProjects);
            MasterVeiw.DataBind();
            LanguageCodeDDl.SelectedValue = Session["LanguageCode"].ToString();

        }

        protected void DetailsVeiw_ItemInserting(object sender, FormViewInsertEventArgs e)
        {
            if (((TextBox)DetailsVeiw.FindControl("OperationYear")).Text == "")
                e.Values["OperationYear"] = 0;
            if (((TextBox)DetailsVeiw.FindControl("InstalledCapacity")).Text == "")
                e.Values["InstalledCapacity"] = 0;
            if (((TextBox)DetailsVeiw.FindControl("EnergyProducedPerYearRate")).Text == "")
                e.Values["EnergyProducedPerYearRate"] = 0;
            if (((DropDownList)DetailsVeiw.FindControl("ddType")).SelectedIndex != -1)
                e.Values["TypeId"] = ((DropDownList)DetailsVeiw.FindControl("ddType")).SelectedValue;
            if (LanguageCodeDDl.SelectedIndex != -1 && LanguageCodeDDl.SelectedValue != "")
                e.Values["LanguageCode"] = LanguageCodeDDl.SelectedValue;
        }

        protected void DetailsVeiw_ItemUpdating(object sender, FormViewUpdateEventArgs e)
        {

            if (((TextBox)DetailsVeiw.FindControl("OperationYear")).Text == "")
                e.NewValues["OperationYear"] = 0;
            if (((TextBox)DetailsVeiw.FindControl("InstalledCapacity")).Text == "")
                e.NewValues["InstalledCapacity"] = 0;
            if (((TextBox)DetailsVeiw.FindControl("EnergyProducedPerYearRate")).Text == "")
                e.NewValues["EnergyProducedPerYearRate"] = 0;
            if (((DropDownList)DetailsVeiw.FindControl("ProjectGroup")).SelectedIndex != -1)
                e.NewValues["ProjectGroupId"] = ((DropDownList)DetailsVeiw.FindControl("ProjectGroup")).SelectedValue;
            if (LanguageCodeDDl.SelectedIndex != -1 && LanguageCodeDDl.SelectedValue != "")
                e.NewValues["LanguageCode"] = LanguageCodeDDl.SelectedValue;

            if (((DropDownList)DetailsVeiw.FindControl("ddExecutingAgency")).SelectedIndex != -1 && ((DropDownList)DetailsVeiw.FindControl("ddExecutingAgency")).SelectedValue != "")
                e.NewValues["ExecutingAgencyId"] = ((DropDownList)DetailsVeiw.FindControl("ddExecutingAgency")).SelectedValue;
            else
                e.NewValues["ExecutingAgencyId"] = 0;

            e.NewValues["TypeId"] = ((DropDownList)DetailsVeiw.FindControl("ddTypeEdit")).SelectedValue;
            e.NewValues["ProjectId"] = ((HiddenField)DetailsVeiw.FindControl("ProjectId")).Value;

        }




        protected void EditButton_Click(object sender, EventArgs e)
        {
            LanguageCodeDDl.Visible = true;
            Language.Visible = true;
        }

        protected void NewButton_Click(object sender, EventArgs e)
        {
            LanguageCodeDDl.Visible = true;
            Language.Visible = true;
        }

        public bool Can(string permission, int CountryId)
        {
            if (Session["dtPermissions"] == null)
            {
                #region Table Permissions
                // Table declarations
                DataTable dtPermissions = new DataTable();

                dtPermissions.Columns.Add("CountryId", typeof(int));
                dtPermissions.Columns.Add("CanAdd", typeof(bool));
                dtPermissions.Columns.Add("CanUpdate", typeof(bool));
                dtPermissions.Columns.Add("CanDelete", typeof(bool));

                // New Row .. assigning permissions
                DataRow drPermission = dtPermissions.NewRow();
                drPermission["CountryId"] = 1;
                drPermission["CanAdd"] = false;
                drPermission["CanUpdate"] = false;
                drPermission["CanDelete"] = false;

                dtPermissions.Rows.Add(drPermission);

                Session.Remove("dtPermissions");

                // Add table to the session object
                Session.Add("dtPermissions", dtPermissions);
                #endregion
            }

            DataRow[] dr = ((DataTable)Session["dtPermissions"]).Select("CountryId = " + CountryId.ToString());

            if (dr.Length > 0)
            {
                return Convert.ToBoolean(dr[0]["Can" + permission]);
            }
            else
                return false;
        }

        protected void DetailsVeiw_ModeChanging(object sender, FormViewModeEventArgs e)
        {
            if (e.CancelingEdit)
                AddNewLB.Visible = Can("Add", Convert.ToInt32(CountriesDD.SelectedValue));

        }

        protected void DetailsVeiw_ItemDeleted(object sender, FormViewDeletedEventArgs e)
        {
            MasterVeiw.DataBind();
        }

        protected void DetailsVeiw_ItemUpdated(object sender, FormViewUpdatedEventArgs e)
        {
            MasterVeiw.DataBind();
            LanguageCodeDDl.SelectedValue = Session["LanguageCode"].ToString();
        }

        protected void LanguageCodeDDl_SelectedIndexChanged(object sender, EventArgs e)
        {
            DetailsVeiw.DataBind();
            if (DetailsVeiw.CurrentMode == FormViewMode.Edit)
            {
                DataTable dt = new DataTable();
                dt = Project.SelectProjectById2(Convert.ToInt32(((HiddenField)DetailsVeiw.FindControl("ProjectId")).Value));
                ((DropDownList)DetailsVeiw.FindControl("ddCountryProject")).SelectedValue = dt.Rows[0]["CountryId"].ToString();
                ((DropDownList)DetailsVeiw.FindControl("ProjectGroup")).SelectedValue = dt.Rows[0]["ProjectGroupId"].ToString();
                ((DropDownList)DetailsVeiw.FindControl("ddTypeEdit")).SelectedValue = dt.Rows[0]["TypeId"].ToString();




                ((CheckBox)DetailsVeiw.FindControl("IsElectrical")).Checked = Convert.ToBoolean(dt.Rows[0]["IsElectrical"]);
                ((CheckBox)DetailsVeiw.FindControl("IsThermal")).Checked = Convert.ToBoolean(dt.Rows[0]["IsThermal"]);
                ((CheckBox)DetailsVeiw.FindControl("IsImplemented")).Checked = Convert.ToBoolean(dt.Rows[0]["IsImplemented"]);


                ((DropDownList)DetailsVeiw.FindControl("DropDownList1")).SelectedValue = dt.Rows[0]["SectorId"].ToString();
                ((DropDownList)DetailsVeiw.FindControl("DropDownList2")).SelectedValue = dt.Rows[0]["StatusId"].ToString();


            }


        }
        public override void VerifyRenderingInServerForm(Control control)
        {



        }
        protected void LinkButton1_Click(object sender, EventArgs e)
        {
            try
            {/*
                Response.Clear();
                Response.AddHeader("content-disposition", "attachment;filename=GridView1.xls");
                Response.Charset = "";
                Response.ContentType = "application/vnd.xls";
                StringWriter StringWriter = new System.IO.StringWriter();
                HtmlTextWriter HtmlTextWriter = new HtmlTextWriter(StringWriter);

                MasterVeiw.RenderControl(HtmlTextWriter);
                Response.Write(StringWriter.ToString());

                //I deleted a line response.End() And Add this line 
                HttpContext.Current.ApplicationInstance.CompleteRequest();
              

                //Microsoft.Office.Interop.Excel.ApplicationClass ExcelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
                //ExcelApp.Application.Workbooks.Add(Type.Missing);

                //// Change properties of the Workbook 
                //ExcelApp.Columns.ColumnWidth = Ms.Rows.Count;

                //// Storing header part in Excel
                //for (int i = 1; i < Ms.Columns.Count + 1; i++)
                //{
                //    ExcelApp.Cells[1, i] = Ms.Columns[i - 1].HeaderText;
                //}

                //// Storing Each row and column value to excel sheet
                //for (int i = 0; i < Ms.Rows.Count - 1; i++)
                //{
                //    for (int j = 0; j < Ms.Columns.Count; j++)
                //    {
                //        ExcelApp.Cells[i + 2, j + 1] =Ms.Rows[i].Cells[j].Value.ToString();

                //    }
                //}

                //ExcelApp.ActiveWorkbook.SaveCopyAs("C:/Users/mariam/Documents/test.xlsx");
                //ExcelApp.ActiveWorkbook.Saved = true;
                //ExcelApp.Quit();
            */




                Response.Clear();

                Response.AddHeader("content-disposition", "attachment; filename=\"Projects.xls\"");

                Response.Charset = "";

                // If you want the option to open the Excel file without saving than

                // comment out the line below

                Response.Cache.SetCacheability(HttpCacheability.NoCache);

                Response.ContentType = "application/octet-stream";

                System.IO.StringWriter stringWrite = new System.IO.StringWriter();

                System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

                MasterVeiw.RenderControl(htmlWrite);

                Response.Write(stringWrite.ToString());

                HttpContext.Current.ApplicationInstance.CompleteRequest();
            }
            catch (Exception exc)
            {

            }
        }

        protected void MasterVeiw_SelectedIndexChanged(object sender, EventArgs e)
        {
            LanguageCodeDDl.SelectedValue = Session["LanguageCode"].ToString();
        }




        protected void Button1_Click(object sender, EventArgs e)
        {
            List<string> validColumns = new List<string> { "Name", "ProjectType", "Place", "OperationYear", "ExecutingAgency" };
            var dataTable = DataManager.SelectProjectsByCountry(Convert.ToInt32(Session["LanguageCode"]),
                                                                Convert.ToInt32(CountriesDD.SelectedValue),
                                                                Convert.ToInt32(Request["E"]));
            ExportToExcel(dataTable, validColumns);
        }

        private void ExportToExcel(DataTable dataTable, List<string> validColumns)
        {
            try
            {

                GridView gridView = Helper.ExportToExcel(dataTable, validColumns);


                Response.Clear();

                Response.AddHeader("content-disposition", "attachment; filename=\"Product Numbers Generated on (" + DateTime.Now.Date.ToString("d MMM yyyy") + ").xls\"");

                Response.Charset = "";

                // If you want the option to open the Excel file without saving than

                // comment out the line below

                Response.Cache.SetCacheability(HttpCacheability.NoCache);

                Response.ContentType = "application/vnd.xls";

                System.IO.StringWriter stringWrite = new System.IO.StringWriter();

                System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

                gridView.RenderControl(htmlWrite);

                Response.Write(stringWrite.ToString());

                Response.End();
            }
            catch (Exception exc)
            {
                throw exc;
            }
        }
    }
}
